/**
 * 知识库API服务
 */
import { callTencentCloudAPI, uploadFileToCOS } from '../utils/tencentCloud';
import { tencentCloudConfig } from '../utils/config';
import type { Category, Document, PaginatedResult, StorageCredential } from '../types';

/**
 * 获取文档分类列表
 * @returns 分类树数组
 */
export const getDocCategories = async (): Promise<Category[]> => {
  const response = await callTencentCloudAPI<{ List: Category[] }>('ListDocCate', {
    BotBizId: tencentCloudConfig.botBizId,
  });
  
  return response.code === 0 ? response.data.List : [];
};

/**
 * 创建文档分类
 * @param name 分类名称
 * @param parentBizId 父分类ID
 * @returns 新创建的分类ID
 */
export const createDocCategory = async (name: string, parentBizId: string): Promise<string> => {
  const response = await callTencentCloudAPI<{ CateBizId: string }>('CreateDocCate', {
    BotBizId: tencentCloudConfig.botBizId,
    ParentBizId: parentBizId,
    Name: name,
  });
  
  return response.code === 0 ? response.data.CateBizId : '';
};

/**
 * 删除文档分类
 * @param cateBizId 分类ID
 * @returns 是否删除成功
 */
export const deleteDocCategory = async (cateBizId: string): Promise<boolean> => {
  const response = await callTencentCloudAPI<{}>('DeleteDocCate', {
    BotBizId: tencentCloudConfig.botBizId,
    CateBizId: cateBizId,
  });
  
  return response.code === 0;
};

/**
 * 修改文档分类名称
 * @param cateBizId 分类ID
 * @param name 新分类名称
 * @returns 是否修改成功
 */
export const updateDocCategory = async (cateBizId: string, name: string): Promise<boolean> => {
  const response = await callTencentCloudAPI<{}>('ModifyDocCate', {
    BotBizId: tencentCloudConfig.botBizId,
    CateBizId: cateBizId,
    Name: name,
  });
  
  return response.code === 0;
};

/**
 * 获取文档列表
 * @param pageNumber 页码
 * @param pageSize 每页数量
 * @param query 搜索关键词
 * @param cateBizId 分类ID
 * @returns 分页后的文档列表
 */
export const getDocuments = async (
  pageNumber: number = 1,
  pageSize: number = 10,
  query: string = '',
  cateBizId?: string
): Promise<PaginatedResult<Document>> => {
  const params: Record<string, any> = {
    BotBizId: tencentCloudConfig.botBizId,
    PageNumber: pageNumber,
    PageSize: pageSize,
  };
  
  if (query) {
    params.Query = query;
  }
  
  if (cateBizId) {
    params.CateBizId = cateBizId;
  }
  
  const response = await callTencentCloudAPI<{ Total: string, List: Document[] }>('ListDoc', params);
  
  if (response.code === 0) {
    return {
      total: response.data.Total,
      list: response.data.List,
    };
  }
  
  return {
    total: '0',
    list: [],
  };
};

/**
 * 获取文档详情
 * @param docBizId 文档ID
 * @returns 文档详情对象
 */
export const getDocumentDetail = async (docBizId: string): Promise<Document | null> => {
  const response = await callTencentCloudAPI<Document>('DescribeDoc', {
    BotBizId: tencentCloudConfig.botBizId,
    DocBizId: docBizId,
  });
  
  return response.code === 0 ? response.data : null;
};

/**
 * 获取上传凭证
 * @param fileType 文件类型
 * @returns 上传凭证对象
 */
export const getStorageCredential = async (fileType: string): Promise<StorageCredential | null> => {
  const response = await callTencentCloudAPI<StorageCredential>('DescribeStorageCredential', {
    BotBizId: tencentCloudConfig.botBizId,
    FileType: fileType,
    IsPublic: false,
  });
  
  return response.code === 0 ? response.data : null;
};

/**
 * 上传文档保存至知识库
 * @param file 文件对象
 * @param storageCredential 上传凭证
 * @param cateBizId 分类ID
 * @returns 文档ID
 */
export const saveDocument = async (
  file: File,
  storageCredential: StorageCredential,
  cateBizId?: string
): Promise<string | null> => {
  try {
    // 先上传文件到COS
    await uploadFileToCOS(file, storageCredential.uploadPath, storageCredential.credentials);
    
    // 上传成功后，保存文档信息
    const response = await callTencentCloudAPI<{ DocBizId: string }>('SaveDoc', {
      BotBizId: tencentCloudConfig.botBizId,
      FileName: file.name,
      FileType: file.name.split('.').pop(),
      CosUrl: storageCredential.uploadPath,
      ETag: 'sample-etag', // 实际应用中应从COS上传响应中获取
      CosHash: 'sample-hash', // 实际应用中应从COS上传响应中获取
      Size: String(file.size),
      Source: 0, // 源文件导入
      AttrRange: 1,
      CateBizId: cateBizId,
    });
    
    return response.code === 0 ? response.data.DocBizId : null;
  } catch (error) {
    console.error('上传文档失败:', error);
    return null;
  }
};

/**
 * 删除文档
 * @param docBizId 文档ID
 * @returns 是否删除成功
 */
export const deleteDocument = async (docBizId: string): Promise<boolean> => {
  const response = await callTencentCloudAPI<{}>('DeleteDoc', {
    BotBizId: tencentCloudConfig.botBizId,
    DocBizIds: [docBizId],
  });
  
  return response.code === 0;
};

/**
 * 生成文档问答
 * @param docBizId 文档ID
 * @returns 是否生成成功
 */
export const generateDocQA = async (docBizId: string): Promise<boolean> => {
  const response = await callTencentCloudAPI<{}>('GenerateQA', {
    BotBizId: tencentCloudConfig.botBizId,
    DocBizIds: [docBizId],
  });
  
  return response.code === 0;
}; 